package de.bazinga.rotw.network;

import de.bazinga.rotw.menu.LANMenu;
import de.bazinga.rotw.util.NetworkConstants;


public class NetworkScan extends Thread {
	
	private LANMenu menu = null;
	
	private Thread scanner1;
	private Thread scanner2;
	private Thread scanner3;
	private Thread scanner4;
	private Thread scanner5;
	
	private String localIP;
	
	public NetworkScan(LANMenu menu) {
		this.menu = menu;
	}
	
	/*public static void main(String[] args) {
		NetworkScan ns = new NetworkScan();
		ns.scanLanForHosts();
	}*/
	
	public void scanLanForHosts() {
		// Remove old games
		LANGames.getInstance().clearGames();
		
		if(localIP==null) {
			localIP = NetworkConstants.getInstance().getLocalIP();
		}
		
		if(localIP!=null) {
			System.out.println("Local IP: "+localIP);
			scanner1 = new NetScanThread(this,0,localIP);
			scanner2 = new NetScanThread(this,50,localIP);
			scanner3 = new NetScanThread(this,100,localIP);
			scanner4 = new NetScanThread(this,150,localIP);
			scanner5 = new NetScanThread(this,200,localIP);
			
			scanner1.start();
			scanner2.start();
			scanner3.start();
			scanner4.start();
			scanner5.start();
		}			
	}
	
	public void stopScanning() {
		if(scanner1 != null) scanner1.interrupt();
		if(scanner2 != null) scanner2.interrupt();
		if(scanner3 != null) scanner3.interrupt();
		if(scanner4 != null) scanner4.interrupt();
		if(scanner5 != null) scanner5.interrupt();
		
		System.out.println("Aborted Scanning");
	}
	
	/**
	 * internal callBack function which is invoked by the
	 * NetScanThread if it has found an server hosting a game.
	 * @param hostIP of the server found in the LAN
	 */
	public synchronized void hostFound(String hostIP) {
		// Add Game to the List
		LANGames.getInstance().addGame(hostIP);
		
		// Tell the Menu that we found a new Server
		menu.updateServerList();
		
		System.out.println("Host found: "+hostIP+" listening on Port "+NetworkConstants.SERVER_TCP_PORT);
	}
}
